package models

import (
	"log"
	"time"
	"xorm.io/builder"
)

type Car struct {
	Id              int64     `xorm:"not null pk autoincr comment('自增主键') INT(11)"`
	InstitutionCode string    `xorm:"comment('运管统一编号') CHAR(16)"`
	SchoolId        int       `form:"school_id" xorm:"not null comment('驾校id，外键关联dts_school表中的id') index INT(11)"`
	PlateNumber     string    `form:"plate_number" xorm:"not null comment('教练车车牌号') unique VARCHAR(16)"`
	Manufacture     string    `form:"manufacture" xorm:"comment('生产厂家') VARCHAR(256)"`
	Brand           string    `form:"brand" xorm:"default '' comment('教练车品牌') VARCHAR(256)"`
	CarSerial       string    `form:"car_serial" xorm:"default '' comment('教练车车架号') VARCHAR(32)"`
	EnginSerial     string    `form:"engin_serial" xorm:"default '' comment('教练车发动机型号') VARCHAR(32)"`
	Color           string    `form:"color" xorm:"default '' comment('教练车颜色') VARCHAR(8)"`
	Model           string    `form:"model" xorm:"comment('车辆型号') VARCHAR(128)"`
	PurchaseDate    string    `xorm:"comment('教练车购买时间')"`
	TrainingType    string    `form:"training_type" xorm:"default 'C1' comment('培训车型') index ENUM('A1','A2','A3','B1','B2','C1','C2','C3','C4','C5','D','E','F','M','N','P')"`
	Status          string    `form:"status" xorm:"default '0' comment('教练车当前工作状态0：停库，1：教学行驶，2：非教学行驶') ENUM('0','1','2')"`
	ApprovalStatus  string    `xorm:"default '0' comment('教练车提交运管审核状态，0:待审核，1:通过审核，2:未通过审核') ENUM('0','1','2')"`
	RecordStatus    string    `xorm:"not null default '0' comment('备案状态 0:未备案 1:已备案') ENUM('0','1')"`
	RecordStatus2   string    `xorm:"not null default '0' comment('濮阳备案状态 0:未备案 1:已备案') ENUM('0','1')"`
	OnServiceDate   time.Time `xorm:"DATE"`
	OutServiceDate  time.Time `xorm:"DATE"`
	Framenum        string    `form:"framenum" xorm:"comment('车架号') VARCHAR(20)"`
	Engnum          string    `form:"engnum" xorm:"comment('发动机号') VARCHAR(20)"`
	Remark          string    `xorm:"VARCHAR(255)"`
	Isused          string    `xorm:"not null default '1' comment('1 可用  0已删除') ENUM('0','1')"`
	HisplateNumber  string    `xorm:"VARCHAR(255)"`
	EnergyType      string    `xorm:"not null default '0' comment('源类型 0:汽油1:柴油2:电3:混合油4:天然气 5:液化石油气6:甲醇7：乙醇8：太阳能9：氢10：生物燃料11：二甲醚12：汽油混合动力13：柴油混合动力14：气体燃料混合动力15：其他')"`
	Number          int       `xorm:"-"`
}

type CarInformation struct {
	Id              int    `json:"id"`
	Sim             string `json:"sim"`
	InstitutionCode string `json:"institution_code"`
	Imei            string `json:"imei"`
	SchoolName      string `json:"school_name"`
	PlateNumber     string `json:"plate_number"`
	TrainingType    string `json:"training_type"`
	RecordStatus    string `json:"record_status"`
	ApprovalStatus  string `json:"approval_status"`
	CarSerial       string `json:"car_serial"`
	Manufacture     string `json:"manufacture"`
	Brand           string `json:"brand"`
	Status          string `json:"status"`
}

func (c *Car) GetCarByFilter(filter builder.Cond, pageSize, offset int) (count int64, list []*CarInformation, err error) {
	err = engine.Table("dts_car").Alias("car").
		Select("car.id,car.institution_code,tl.imei,car.plate_number,car.training_type,car.record_status,car.approval_status,tc.sim,sl.name_short as school_name,car.car_serial,car.manufacture,car.brand,car.status").
		//Join("left", []string{"dts_car_portrait", "cp"}, "car.id = cp.car_id").
		Join("LEFT", []string{"dts_terminal_car", "tc"}, "tc.car_id=car.id").
		Join("left", []string{"dts_terminal", "tl"}, "tl.id = tc.terminal_id").
		Join("left", []string{"dts_school", "sl"}, "sl.id = car.school_id").
		And(filter).Limit(pageSize, offset).Desc("car.id").Find(&list)
	count, err = engine.Table("dts_car").Alias("car").
		//Join("left", []string{"dts_car_portrait", "cp"}, "car.id = cp.car_id").
		Join("LEFT", []string{"dts_terminal_car", "tc"}, "tc.car_id=car.id").
		Join("left", []string{"dts_terminal", "tl"}, "tl.id = tc.terminal_id").
		Join("left", []string{"dts_school", "sl"}, "sl.id = car.school_id").
		And(filter).Count()
	log.Print(err)
	return
}

func (c *Car) GetOneCarById(Id int64) (list Car, err error) {
	_, err = engine.Table("dts_car").Where("id=? and isused=?", Id, "1").Get(&list)
	return list, err
}

func (c *Car) GetCarByNumber(platenumber string) (has bool, list Car, err error) {
	has, err = engine.Table("dts_car").Where("plate_number = ? and isused = ?", platenumber, "1").Get(&list)
	return
}

// types 1 添加   2 编辑
func (c *Car) HasPlateNumber(types int) bool {
	if types == 1 {
		has, err := engine.Table("dts_car").Where("plate_number = ? && isused=?", c.PlateNumber, "1").Exist()
		if has && err == nil {
			return true
		} else {
			return false
		}
	} else {
		car := new(Car)
		if _, err := engine.Table("dts_car").Where("plate_number = ? && isused=?", c.PlateNumber, "1").Get(car); err != nil {
			return false
		} else {
			//phone 已经重复
			if c.Id == car.Id {
				//phone 没有变化
				return false
			} else {
				//已经存在该phone了
				return true
			}
		}
	}
	return true
}
